<template>
	<canvas type="webgl" id="webgl" style="width: 100vw; height: 100vh"></canvas>
</template>

<script setup>
import { createScopedThreejs } from 'threejs-miniprogram';
import { onReady } from '@dcloudio/uni-app';
 import { registerGLTFLoader } from '@/utils/gltf-loader_new_new.js';
 
let THREE = null;
let canvas = null;
 
onReady(() => {
	init();
});
  
 
 
function createThree() {
	return new Promise((resolve) => {
		uni.createSelectorQuery()
			.select('#webgl')
			.node()
			.exec((res) => {
				//canvas做动画时要用
				canvas = res[0].node;
				// 创建一个与 canvas 绑定的 three.js
				THREE = createScopedThreejs(canvas);
				resolve();
			});
	});
}

let renderer = null
 
 
function createRenderer() {
	renderer = new THREE.WebGLRenderer();
	renderer.setSize(canvas.width, canvas.height);
}

let scene = null;
let camera = null;
 
async function init() {
	await createThree();
	createRenderer();
	createScene();
	createCamera();
	createLight();
	registerGLTFLoader(THREE);
	//glb纹理需要blob,小程序没有
	const res = await loadGLTF('https://cttxhy-1360132035.cos.ap-shanghai.myqcloud.com/characters/Fox.gltf');
	res.position.set(0, 0, 0);
	
	// 也可以放到其他位置，例如
	// res.position.set(10, 5, -20);
	
	
	scene.add(res);
	renderer.render(scene, camera);
}
 
function loadGLTF(url) {
	return new Promise((resolve, reject) => {
		new THREE.GLTFLoader().load(url, (gltf) => {
			// gltf.scene.scale.set(1, 1, 1);
			resolve(gltf.scene);
		});
	});
}
 
function createLight() {
	const light = new THREE.AmbientLight(0xffffff);
	scene.add(light);
}
 
function createScene() {
  scene = new THREE.Scene();
  scene.background = new THREE.Color(0x000000); // 背景换成黑色
}
 
function createCamera() {
  camera = new THREE.PerspectiveCamera(75, canvas.width / canvas.height, 0.1, 1000);
  camera.position.set(3, 7, 15); // 位置挪近一点，离模型更近
  camera.lookAt(0, 0, 0);
}
</script>